<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
        <el-form-item>
          <el-select
            filterable
            placeholder="一级类别"
            v-model="formInline.first_type"
            @change="second_type"
            style="width:100px;"
          >
            <el-option
              v-for="item in first_type_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            filterable
            placeholder="二级类别"
            v-model="formInline.second_type"
            @change="type"
            style="width:100px;"
          >
            <el-option
              v-for="item in second_type_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable placeholder="三级类别" v-model="formInline.type" style="width:100px;">
            <el-option v-for="item in type_list" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="formInline.gift_id"
            placeholder="请输入礼品编号/名称"
            @keyup.enter.native="searchClick"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="图片" width="80">
          <template slot-scope="scope">
            <div v-viewer="options" class="images fit">
              <img
                :src="scope.row.thumb"
                :data-source="scope.row.img"
                class="image"
                :key="scope.row.img"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="礼品名称" prop="name"></el-table-column>
        <el-table-column align="center" label="礼品编号" prop="id"></el-table-column>
        <el-table-column align="center" label="神采礼品编号" prop="no_obsolete"></el-table-column>
        <el-table-column align="center" label="箱规" prop="box_num">
          <template slot-scope="scope">{{scope.row.box_num == 0 ?'-':scope.row.box_num}}</template>
        </el-table-column>

        <el-table-column align="center" label="类别" prop="type_name"></el-table-column>
        <el-table-column align="center" label="总部进货价" prop="money_cost"></el-table-column>
        <el-table-column align="center" label="前台销售">
          <template slot-scope="scope">{{scope.row.is_store_on_sale==1?'支持':'-'}}</template>
        </el-table-column>
        <el-table-column align="center" label="会员兑换票数">
          <template slot-scope="scope">{{scope.row.ticket_value_vip?scope.row.ticket_value_vip:'-'}}</template>
        </el-table-column>
        <el-table-column align="center" label="非会员兑换票数">
          <template slot-scope="scope">{{scope.row.ticket_value?scope.row.ticket_value:'-'}}</template>
        </el-table-column>
        <el-table-column align="center" label="兑换积分">
          <template slot-scope="scope">{{scope.row.integral?scope.row.integral:'-'}}</template>
        </el-table-column>
        <el-table-column align="center" label="图片管理">
          <template slot-scope="scope">
            <el-button type="text" @click="updateImg(scope.row.id)">
              <span style="font-size: 22px" class="el-icon-edit"></span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹框 -->
      <el-dialog width="800px" title="图片管理" :visible.sync="addhouseDialog">
        <div style="position:absolute;top:60px;">
          <span class="title">已使用图片</span>
          <span class="subTitle">选中图片作为展示图片</span>
        </div>
        <div style="display: flex;margin-top: 10px;min-height: 80px;">
          <div v-for="(u,i) in used" :key="u.id">
            <el-checkbox v-model="radio" :true-label="u.id" false-label="0">
              <div class="images fit" style="width:80px;height:80px">
                <img style="vertical-align:middle" :src="u.src" />
              </div>
            </el-checkbox>
            <i @click="delUsed(u,i)" class="el-icon-circle-close"></i>
          </div>
        </div>
        <hr style="margin-top:20px" />
        <div style="position:absolute;top:200px;display: flex;line-height: 33px">
          <span class="title">图片收藏夹</span>
          <el-upload
            class="upload-demo"
            :multiple="multiple"
            action="123"
            :http-request="uploadFile"
            :show-file-list="false"
            ref="upload"
            accept=".jpg, .jpeg, .png, .JPG, .JPEG"
          >
            <el-button icon="el-icon-upload2" size="small" type="primary">上传</el-button>
          </el-upload>
        </div>
        <div style="display:flex;margin-top:50px;min-height: 80px;">
          <div v-for="(c,i) of collect" :key="c.id">
            <i @click="addUsed(i)" class="el-icon-circle-plus-outline"></i>
            <!-- <img style="vertical-align:middle" width="80px" height="80px" :src="c.src" alt> -->
            <div
              class="images fit"
              style="width:80px;height:80px;vertical-align:middle;display:inline-block"
            >
              <img :src="c.src" alt />
            </div>
            <i @click="delCollect(i)" class="el-icon-circle-close"></i>
          </div>
        </div>

        <!-- 
                <div v-for="(u,i) in used"  :key="u.id"style="margin-top:10px">
                    <el-radio  v-model="radio" :label="u.id" style="margin:0">
                        <img style="vertical-align:middle" width="80px" height="80px" :src="u.src" alt>
                        <i @click="delUsed(u,i)" class="el-icon-circle-close-outline"></i>
                    </el-radio>
                </div>
                <hr style="margin-top:20px">
                <div style="position:absolute;top:210px;">
                    <span class="title">图片收藏夹</span>
                    <span @click="uploadImg" class="el-icon-upload2"
                        style="color:#409EFF;font-size:20px;cursor: pointer;"></span>
                </div>
                <div style="display:flex;margin-top:50px;">
                    <div v-for="(c,i) of collect" :key="c.id">
                        <i @click="addUsed(i)" class="el-icon-circle-plus-outline"></i>
                        <img style="vertical-align:middle" width="80px" height="80px" :src="c.src" alt>
                        <i @click="delCollect(i)" class="el-icon-circle-close-outline"></i>
                    </div>
        </div>-->
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submit">确认提交</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-pagination
        class="pull-left"
        background
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="20"
        layout="prev, pager, next, jumper"
        :total="totalDataNumber"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getList,
  getPage,
  get_type,
  get_img,
  update_img,
  upload_img,
  check_img,
} from "@/api/information/gift";
import { getSts } from "@/api/feedback";
import axios from "axios";
export default {
  data() {
    return {
      radio: 0,
      multiple: true,
      // imglimit:3,
      imgList: { file: "" },
      addhouseDialog: false,
      machineInfo: "",
      list: null,
      first_type_list: null,
      second_type_list: null,
      type_list: null,
      listLoading: false,
      currentPage: 1,
      totalDataNumber: 0,
      giftId: "",
      options: {
        //预览图配置
        toolbar: true,
        url: "data-source",
      },
      userInfo: {},
      formInline: {
        size: "",
        first_type: "",
        second_type: "",
        type: "",
        gift_id: "",
        category_id: 20,
      },
      resUsed: [],
      resCollect: [],
      resRadio: 0,
      used: [],
      collect: [],
      del: [],
      saveData: {
        gift_id: "",
        is_use: [],
        fav: [],
        del: [],
        show: "",
      },
    };
  },
  created() {
    this.first_type();
    this.searchClick();
    this.userInfo = JSON.parse(localStorage.getItem("USER_INFO"));
  },
  methods: {
    // 搜索
    searchClick() {
      this.fetchData();
      // this.getSize();
    },
    first_type() {
      get_type({ id: 0 }).then((response) => {
        this.first_type_list = response;
      });
    },
    second_type(id) {
      this.listLoading = true;
      this.formInline.second_type = "";
      this.formInline.type = "";
      get_type({ id: id })
        .then((response) => {
          this.second_type_list = response;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    type(id) {
      this.formInline.type = "";
      this.listLoading = true;
      get_type({ id: id })
        .then((response) => {
          this.type_list = response;
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      this.currentPage = 1;
      getPage(this.formInline)
        .then((response) => {
          this.totalDataNumber = response * 20;
          getList(this.formInline).then((response) => {
            response.forEach((val, i) => {
              val.money_cost = ((val.money_cost * 1) / 1000000).toFixed(2);
            });
            this.list = response;
            this.listLoading = false;
          });
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    // 分页
    handleCurrentChange(val) {
      this.listLoading = true;
      getList(this.formInline, val).then((response) => {
        response.forEach(function (val, i) {
          val.money_cost = ((val.money_cost * 1) / 1000000).toFixed(2);
        });
        this.list = response;
        this.listLoading = false;
      });
    },
    //获取管理图片
    async updateImg(id) {
      this.listLoading = true;
      this.used = [];
      this.collect = [];
      this.del = [];
      this.resUsed = [];
      this.resCollect = [];
      this.radio = "";
      this.giftId = id;
      this.addhouseDialog = true;
      try {
        let res = await get_img({ gift_id: id });
        //console.log(res)
        if (res.use) {
          for (var u of res.use) {
            this.used.push({
              id: u.id,
              src: "https://img.hahaipi.com/" + u.url,
            });
            this.resUsed.push({
              id: u.id,
              src: "https://img.hahaipi.com/" + u.url,
            });
          }
        }
        if (res.show) {
          this.radio = res.show;
          this.resRadio = res.show;
        } else {
          this.resRadio = 0;
        }
        if (res.fav) {
          for (var f of res.fav) {
            this.collect.push({
              id: f.id,
              src: "https://img.hahaipi.com/" + f.url,
            });
            this.resCollect.push({
              id: f.id,
              src: "https://img.hahaipi.com/" + f.url,
            });
          }
        }
        // this.imglimit=6-(this.used.length+this.collect.length);
        this.listLoading = false;
      } catch (err) {
        this.$message.error(err);
        this.listLoading = false;
      }
    },
    //移除已使用的图片
    delUsed(u, i) {
      //console.log(u.id, this.radio);
      this.collect.push(this.used.splice(i, 1)[0]);
      if (u.id == this.radio) {
        if (this.used.length > 0) this.radio = this.used[0].id;
        else this.radio = "";
      }
      // console.log(this.collect);
    },
    //移除收藏夹中的图片
    delCollect(i) {
      this.del.push(this.collect.splice(i, 1)[0]);
      //console.log(this.del);
    },
    //将收藏夹中的图片移至已使用
    addUsed(i) {
      this.used.push(this.collect.splice(i, 1)[0]);
      if (this.used.length == 1) this.radio = this.used[0].id;
      // console.log(this.used);
    },
    //上传图片
    uploadFile(file) {
      // if(this.imglimit==0){
      //     this.$message({ type: 'error', message: "最多只能有6张图片哦！" });
      //     return ;
      // }
      console.log(location.host, "host");
      let folder_name =
        location.host == "scfy.i3020.com" || location.host == "ims.i3020.com"
          ? "gift"
          : "giftdev";
      this.imgList.file = file.file;
      //this.$refs.upload.submit();
      this.loading = true;
      check_img({ gift_id: this.giftId }).then((res) => {
        if (res.code == 1) {
          getSts({}, 2).then((response) => {
            // let host = 'http://src-scfy.oss-cn-hangzhou.aliyuncs.com';
            let host = "https://img.hahaipi.com";
            let policyText = {
              expiration: "2022-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
              conditions: [
                ["content-length-range", 0, 1048576000], // 设置上传文件的大小限制
              ],
            };
            let imgSuffix = this.imgList.file.name.split(".");
            let suffix = imgSuffix[imgSuffix.length - 1];
            //console.log(this.imgList.file.name,suffix)
            let policyBase64 = Base64.encode(JSON.stringify(policyText));
            let bytes = Crypto.HMAC(
              Crypto.SHA1,
              policyBase64,
              response.AccessKeySecret,
              { asBytes: true }
            );
            let signature = Crypto.util.bytesToBase64(bytes);
            let config = {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            };
            let date = new Date();
            let month =
              date.getMonth() < 9
                ? "0" + (date.getMonth() + 1)
                : date.getMonth() + 1;
            let day =
              date.getDate() < 9 ? "0" + date.getDate() : date.getDate();
            let h =
              date.getHours() < 9 ? "0" + date.getHours() : date.getHours();
            let min =
              date.getMinutes() < 9
                ? "0" + date.getMinutes()
                : date.getMinutes();
            let s =
              date.getSeconds() < 9
                ? "0" + date.getSeconds()
                : date.getSeconds();
            let dateYMD = `${date.getFullYear()}${month}${day}`;
            let dateHMS = `${h}${min}${s}`;
            let data = new FormData();
            let imgName = `${folder_name}/${
              this.giftId
            }/${dateYMD}${dateHMS}${this.S4(10000, 99999)}.${suffix}`;
            data.append("key", imgName);
            data.append("policy", policyBase64);
            data.append("OSSAccessKeyId", response.AccessKeyId);
            data.append("success_action_status", 200);
            data.append("x-oss-security-token", response.SecurityToken);
            data.append("signature", signature);
            data.append("file", this.imgList.file);
            axios
              .post(host, data, config)
              .then((res) => {
                //console.log(res,imgName)
                let data = {};
                data.gift_id = this.giftId;
                data.img_list = [];
                data.img_list.push({ img: imgName });
                // data.img_list.img=imgName
                data.uid = this.userInfo.id;
                upload_img(data).then((res) => {
                  //console.log(res,res.code==1,999);
                  if (res.code == 1) {
                    this.$message({ type: "success", message: res.message });
                    this.collect.push({
                      id: res.id,
                      src: "https://img.hahaipi.com/" + imgName,
                    });
                    //console.log(this.collect);
                  }
                });
              })
              .catch((res) => {
                this.$message({ type: "error", message: JSON.stringify(res) });
                console.log(res);
              });
          });
        } else {
          this.$message({ type: "error", message: res.message });
        }
      });
    },
    S4(m, n) {
      return Math.floor(Math.random() * (m - n) + n);
    },
    equal(x, y) {
      if (x.id != y.id) return false;
      else return true;
    },
    //确认提交
    async submit() {
      let isSubmit = true;
      this.addhouseDialog = false;
      if (
        this.resCollect.length != this.collect.length ||
        this.resUsed.length != this.used.length ||
        this.resRadio != this.radio
      ) {
        isSubmit = false;
      } else {
        for (var i in this.used) {
          //console.log(this.equal(this.used[i],this.resUsed[i]))
          if (!this.equal(this.used[i], this.resUsed[i])) isSubmit = false;
        }
      }
      //console.log(this.resUsed,this.used)
      //console.log(isSubmit)
      if (!isSubmit) {
        this.saveData.gift_id = this.giftId;
        this.saveData.show = this.radio;
        var useArr = [];
        var favArr = [];
        var delArr = [];
        for (let u of this.used) {
          useArr.push(u.id);
        }
        this.saveData.is_use = useArr;
        for (let c of this.collect) {
          favArr.push(c.id);
        }
        this.saveData.fav = favArr;
        for (let d of this.del) {
          delArr.push(d.id);
        }
        this.saveData.del = delArr;
        //console.log(this.saveData);
        try {
          let res = await update_img(this.saveData);
          this.$message({
            type: res.code == 1 ? "success" : "error",
            message: res.message,
          });
          if (this.resRadio != this.radio) this.fetchData();
        } catch (err) {
          this.$message.error(err);
        }
      }
    },
  },
};
</script>

<style scpoed>
span.el-icon-circle-plus {
  font-size: 30px;
}

i.el-icon-circle-close {
  vertical-align: top;
  color: #606266;
  font-size: 15px;
  cursor: pointer;
}

i.el-icon-circle-plus-outline {
  vertical-align: middle;
  font-size: 15px;
  cursor: pointer;
  margin: 0 3px 0 2px;
}

div > span.title {
  font-weight: bolder;
  margin: 0 10px 0 20px;
}

div > span.subTitle {
  margin-left: 10px;
  color: #bbb;
}
</style>